﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.Diagnostics;

namespace KeyboardImageViewer
{
    /// <summary>
    /// Interaction logic for EditTagBox.xaml
    /// </summary>
    public partial class EditTagBox : Window
    {
        private const int MaxSuggestedTags = 20;

        private List<string> previousTags;
        private TagAutoCompleteTextBox tagBox;

        public EditTagBox(MainWindow window)
        {
            this.Owner = window;

            InitializeComponent();

            Dictionary<string, int> tagsSummary = Database.GetTagsSummary(ImageManager.Connection);
            this.tagBox = new TagAutoCompleteTextBox { TagsSummary = tagsSummary, Margin = new Thickness(53, 10, 23, 0) };
            this.rootGrid.Children.Add(this.tagBox);

            this.previousTags = ImageManager.CurrentTags;

            if (this.previousTags.Count > 0)
            {
                StringBuilder tagsBuilder = new StringBuilder();

                foreach (string tag in this.previousTags)
                {
                    tagsBuilder.Append(tag);
                    tagsBuilder.Append(" ");
                }

                string tagsText = tagsBuilder.ToString();

                this.tagBox.TextBox.Text = tagsText;
                this.tagBox.TextBox.SelectionStart = tagsText.Length;
                this.tagBox.TextBox.SelectionLength = 0;
            }

            this.tagBox.TextBox.Focus();
        }

        private void tagEditOk_Click(object sender, RoutedEventArgs e)
        {
            string tagString = this.tagBox.TextBox.Text;

            string[] tags = tagString.Split(new char[] { ' ' });

            List<string> tagsResult = new List<string>();

            foreach (string tag in tags)
            {
                string cleanTag = tag.Replace("|", "");
                cleanTag = cleanTag.Replace(",", "");

                if (cleanTag != "")
                {
                    tagsResult.Add(cleanTag.ToLowerInvariant());
                }
            }

            TagOperations.UpdateCurrentTags(this.previousTags, tagsResult);
            this.DialogResult = true;
        }
    }
}
